//
//  GRMyInfomationViewController.m
//  YC_GRice
//
//  Created by LiuFeng on 2018/7/14.
//  Copyright © 2018年 YeCai. All rights reserved.
//

#import "GRMyInfomationViewController.h"
#import "GRRegisterViewController.h"
#import "GRModifyNickNameViewController.h"

#import "GRSystemSettingViewCell.h"
#import "GRMyCommonHeaderView.h"
#import "PhotoBrowerManager.h"
#import "GRChooseGender.h"
#import "GRPersonModel.h"

@interface GRMyInfomationViewController () <GRChooseGenderDelegate, GRPayManagerDelegate>

{
    NSArray *infomations;
    NSString *type;
}

@property (nonatomic, strong) GRPersonModel *personModel;
@property (nonatomic, strong) GRChooseGender *chooseGender;

@end

@implementation GRMyInfomationViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    infomations = @[@"个人头像", @"昵称", @"性别", @"登录密码", @"关联微信", @"关联支付宝"];
    // Uncomment the following line to preserve selection between presentations.
    GRMyCommonHeaderView *headerView = [[GRMyCommonHeaderView alloc] initWithFrame:CGRectMake(0, 0, KscreenWidth, 55)];
    headerView.textLabel.text        = @"个人资料";
    self.tableView.tableHeaderView   = headerView;
    self.tableView.tableFooterView   = [UIView new];
    
    self.tableView.rowHeight         = 50;
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    [self.tableView registerNib:[UINib nibWithNibName:@"GRSystemSettingViewCell" bundle:nil] forCellReuseIdentifier:@"GRSystemSettingViewCell"];
    
    [self getUserProfile];
    
    [GRPayManager sharePay].delegate = self;
}


/**
 获取用户信息
 */
- (void)getUserProfile {
    [GRPersonAction getUserProfile:^(BOOL success, id responseObject, GRError *error) {
        if (success) {
            self.personModel = responseObject;
            [self.tableView reloadData];
        }
    }];
}


/**
 修改用户信息

 @param value <#value description#>
 */
- (void)updateUserProfile:(NSString *)value {
    NSDictionary *param = @{@"type"  : type,
                            @"value" : value};
    WEAKSELF
    [GRPersonAction updateUserProfile:param completionHandler:^(BOOL success, id responseObject, GRError *error) {
        if (success) {
            if ([type isEqualToString:@"avatar"]) {
                weakSelf.personModel.avatar   = value;
            }else {
                weakSelf.personModel.gender   = value;
            }
            [self.tableView reloadData];
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return infomations.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GRSystemSettingViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GRSystemSettingViewCell" forIndexPath:indexPath];
    cell.titleLabel.text = infomations[indexPath.row];
    [cell populateUserInfo:self.personModel atIndexPath:indexPath];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    WEAKSELF
    switch (indexPath.row) {
        case 0:{
            type = @"avatar";
            [[PhotoBrowerManager defaultManager] selectAlongPicture:PhotoBrowserContentModeAll CurrentVc:self FinishBlock:^(NSArray<UIImage *> *images) {
                [[GRUploadManager defaultManager] uploadSingleIMAGE:images.firstObject completion:^(NSString *imgURL, BOOL success) {
                    if (success) {
                        [weakSelf updateUserProfile:imgURL];
                    }
                }];
            }];
        }
            break;
            
        case 1:{
            GRModifyNickNameViewController *nickNameVc = [[GRModifyNickNameViewController alloc] init];
            nickNameVc.nickname   = self.personModel.nickname;
            nickNameVc.completion = ^{
                [weakSelf getUserProfile];
            };
            [self.navigationController pushViewController:nickNameVc animated:YES];
        }
            break;
        case 2:{
            type = @"gender";
            [self.chooseGender showGender];
        }
            break;
        case 3:{
            GRRegisterViewController *registerVc = [[GRRegisterViewController alloc] init];
            registerVc.registerMode = self.personModel.passwordFlag ? GRRegisterModeModifyLoginPassword : GRRegisterModeSetLoginPassword;
            registerVc.finishBlock = ^{
                self.personModel.passwordFlag = YES;
                [self.tableView reloadData];
            };
            [self.navigationController pushViewController:registerVc animated:YES];
        }
            break;
        case 4:{
            if (self.personModel.wechatFlag) {
                [[LFAlertBox defaultAlert] showAlertTitle:@"解绑微信" content:@"确定解绑与微信账号的关联吗？" cancleText:@"暂不解除" sureText:@"解除关联" completion:^(NSInteger index) {
                    if (index == 1) {
                        [GRHUD showLoading:@"解绑中" atView:weakSelf.view];
                        [self bindingWechat:NO paramers:nil];
                    }
                }];
            }else {
                [GRPayManager WechatAuth_WithViewController:self completion:^(UMSocialUserInfoResponse *response) {
                    NSDictionary *param = @{@"avatar" : response.iconurl,
                                            @"name"   : response.name,
                                            @"openId" : response.openid,
                                            @"sex"    : ([response.gender isEqualToString:@"f"] ? @"female" : @"male"),
                                            @"unionId": response.unionId,
                                            @"sourceWechat" : @"app"
                                            };
                    [self bindingWechat:YES paramers:param];
                }];
            }
        }
            break;
            
        default:{
            if (self.personModel.alipayFlag) {
                [[LFAlertBox defaultAlert] showAlertTitle:@"解绑支付宝" content:@"确定解绑与支付宝账号的关联吗？" cancleText:@"暂不解除" sureText:@"解除关联" completion:^(NSInteger index) {
                    if (index == 1) {
                        [GRHUD showLoading:@"解绑中" atView:weakSelf.view];
                        [self bindingAlipay:NO result:nil];
                    }
                }];

            }else {
                [GRPersonAction getAlipayAuth_V2Str:^(BOOL success, id responseObject, GRError *error) {
                    if (success) {
                        [GRPayManager AlipayAuth_V2WithInfo:responseObject completion:^(NSDictionary *resultDic) {
                            if ([resultDic[@"resultStatus"] integerValue] == 9000) {
                                [self bindingAlipay:YES result:resultDic[@"result"]];
                            }
                        }];
                    }
                }];
            }
        }
            break;
    }
}

-(void)alipayResultDic:(NSDictionary *)resultDic {
    if ([resultDic[@"resultStatus"] integerValue] == 9000) {
        [self bindingAlipay:YES result:resultDic[@"result"]];
    }
}


/**
 解绑或绑定 支付宝

 @param isbind <#isbind description#>
 @param result <#paramers description#>
 */
- (void)bindingAlipay:(BOOL)isbind result:(NSString *)result {
    NSDictionary *paramer = nil;
    if (result) {
        NSArray *resultList = [result componentsSeparatedByString:@"&"];
        NSString *authcode  = @"";
        for (int i = 0; i < resultList.count; i++) {
            NSString *key = resultList[i];
            if ([key hasPrefix:@"auth_code"]) {
                authcode = [key stringByReplacingOccurrencesOfString:@"auth_code=" withString:@""];
            }
        }
        paramer = @{@"authCode" : authcode
                    };
    }
WEAKSELF
    [GRPersonAction bindingAlipay:isbind paramer:paramer completionHandler:^(BOOL success, id responseObject, GRError *error) {
        if (!isbind) {
            [GRHUD dismissHUD:weakSelf.view];
        }
        if (success) {
            weakSelf.personModel.alipayFlag = isbind;
            [weakSelf.tableView reloadData];
            if (!isbind) {
                [GRHUD showCustomHud:@"解绑成功" icon:@"usercenter_35" atView:weakSelf.view];
            }
        }
    }];
}



/**
 解绑或绑定 微信

 @param isbind <#iswechat description#>
 @param paramers <#paramers description#>
 */
- (void)bindingWechat:(BOOL)isbind paramers:(NSDictionary *)paramers {
    WEAKSELF
    [GRPersonAction bindingWechat:isbind paramer:paramers completionHandler:^(BOOL success, id responseObject, GRError *error) {
        if (!isbind) {
            [GRHUD dismissHUD:weakSelf.view];
        }
        if (success) {
            weakSelf.personModel.wechatFlag = isbind;
            [weakSelf.tableView reloadData];
            if (!isbind) {
                [GRHUD showCustomHud:@"解绑成功" icon:@"usercenter_35" atView:weakSelf.view];
            }
        }
    }];
}


-(void)didFinishChooseGender:(NSString *)gender {
    [self updateUserProfile:gender];
}


-(GRChooseGender *)chooseGender {
    if (!_chooseGender) {
        _chooseGender = [[GRChooseGender alloc] init];
        _chooseGender.delegate = self;
    }
    return _chooseGender;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
